<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        .divBorder{
            border: 1px solid #000000;
            float: left;
            width: 20%;
            height: 600px;
            overflow-y: auto;
            margin-left: 10px;
        }
        .canBorder{
            float: left;
            background-color: rgba(0, 191, 255, .2);
            border: 1px dashed #000000;
            width: 78%;
            height: 600px;
        }
        .maskDialog{
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.1);
            display: block;
            padding-top: 100px;
            position:fixed;
        }
        .maskDialog .maskTitle{
            width: 40%;
            height: 40px;
            line-height: 40px;
            text-align: center;
            margin: 0 auto;
            background: #00EE00;
        }
        .maskDialog .maskContent{
            width: 40%;
            height: auto;
            margin: 0 auto;
            background: #FFFFFF;
        }
        .maskDialog .maskFloot{
            width: 40%;
            height: auto;
            margin: 0 auto;
            text-align: center;
            background: #FFFFFF;
        }
        .maskDialog .maskContent input{
            width: 100px;
        }
        body{
            -moz-user-select: none;
            padding: 0;
            margin: 0;
        }
        input{
            outline: none;
            width: 70px;
        }
        ul{
            list-style: none;
            padding: 0;
        }
        ul li{
            float: left;
            margin: 8px 0px;
            text-align: center;
        }
        ul li div{
            width: 90px;
            cursor: move;
        }
    </style>

    <script src="../controllers/stacklist_draw.js"></script>
    <script src="../vendors/jquery/dist/jquery.js"></script>
    <link rel="stylesheet" href="../css/stacklist_draw.css">

    <script src="../vendors/bootstrap/dist/js/bootstrap.js"></script>
    <script src="../vendors/bootstrap/extend/Modalz_Bootstrap.min.js"></script>
    <link rel="stylesheet" href="../vendors/bootstrap/dist/css/bootstrap.css">
</head>
<body onselectstart="return false">
<div id="productPoolDiv" class="divBorder">
    <div>
        <input id="lineBtn" type="button" title="连线" class="btnLineNormal" onclick="startLineListener(event);" />
        <input id="deleteProductBtn" type="button" title="删除产品" class="btnDeleteProductNormal" onclick="deleteProductListener(event);" />
        <input id="deleteLineBtn" type="button" title="删除连线" class="btnDeleteLineNormal" onclick="deleteLineListener(event);" />
        <input id="savebtn" type="button" title="删除连线" class="btSaveDrawNormal" onclick="saveline(event);" />
    </div>
    <img src="../images/stacklist_image/d.png" style="display: none;" />
    <ul id="productPoolUL">
        <li>
            <div id="1" ondragstart="drag(event);" draggable="true">
                <img src="../images/stacklist_image/1493273869.png" draggable="false" />
                <div>产品一</div>
            </div>
        </li>
        <li>
            <div id="2" ondragstart="drag(event);" draggable="true">
                <img src="../images/stacklist_image/quoteDependence.png" draggable="false" />
                <div>产品二</div>
            </div>
        </li>
        <li>
            <div id="3" ondragstart="drag(event);" draggable="true">
                <img src="../images/stacklist_image/start.png" draggable="false" />
                <div>产品三</div>
            </div>
        </li>
    </ul>
</div>

<div id="canvasDiv" class="canBorder">
    <canvas id="selectedCanvas" ondragover="allowDrop(event)" ondrop="drawOneProduct(event)">

    </canvas>
</div>
<script type="text/javascript">

    function GetQueryString(name)
    {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]); return null;
    }
    function saveline(event) {
        debugger;
        es;
        relations;
        beginPoint;
        stopPoint;
        var  drawall=new Object()
        drawall.envirId=envirId;
        drawall.imageCoordinate=new Array();
        drawall.lineCoordinate=new Array();

        for(var i=0;i<relations.length;i++) {
            if(typeof(relations[i])=="undefined"||relations[i]==null)
            {
                continue;
            }
            drawall.lineCoordinate.push(relations[i]);
        }
        for (var i=0;i<es.length;i++)
        {
            if(typeof(es[i])=="undefined"||es[i]==null)
            {
                continue;
            }
            drawall.imageCoordinate.push(es[i]);
        }
        JSON.stringify(drawall);
        $.ajax({
            type: "post",
            url: "/api/kuberdrawcoordinate/add",
            data: {model:JSON.stringify(drawall)},
            success: function (res) {

            },
            error: function (res) {
                $.messageBox(res.responseText, "error");
            }
        })
    }
    var dragging = false;//开始拖拽
    var dragProduct;//拖入的数据对象
    var lineing = false;//开始连线
    var deleteLine = false;//开始删除连线
    var deleteProduct = false;//开始删除产品
    var es = [];//服务数据
    var relations = [];//关联信息
    var deleteList = [];//删除图片集合
    var index = 0;//用于选择服务id
    var isDoubleClick = false;//延迟触发点击
    var beginPoint = null;//连线时临时记录起点
    var stopPoint = null;//连线时临时记录终点
    var clickTimeOut = null;//双击单击间隔延迟事件id
    var moveShape;//拖拽目标
    var dblShape;//双击目标
    var envirId;
    $(function(){
        if (!document.getElementById("selectedCanvas").getContext){
            alert("不支持html5");
            return false;
        }

        envirId=GetQueryString("envirId");

        $.ajax({
            type:"get",
            url:"/api/kuberdrawcoordinate/get",
            data:{"envirId":envirId},
            dataType:"json",
            success:function(data){
                if(data.code==100){

                }else{
                    es = data.data.imageCoordinate;
                    //确定index的值
                    for(var i = 0;i<es.length;i++){
                        var product = es[i];
                        if(typeof(product)=="undefined"){
                            continue;
                        }
                        var m = product.id.split("_")[1];
                        if(m>index){
                            index = m;
                        }
                    }
                    relations = data.data.lineCoordinate;
                    drawScreen();
                }
            }
        });
        selectedCanvas.addEventListener("mousedown",mouseDownListener);
        selectedCanvas.addEventListener("mouseup",mouseUpListener);
        selectedCanvas.addEventListener("mousemove",mouseMoveListener);
        selectedCanvas.addEventListener("mouseout",mouseOutListener);
        selectedCanvas.addEventListener("click",clickListener);
        selectedCanvas.addEventListener("dblclick",dblClickListener);
        selectedCanvas.width = canvasDiv.offsetWidth;
        selectedCanvas.height = canvasDiv.offsetHeight;

    });

    function dblClickListener(event){
        if(lineing||deleteLine||deleteProduct){
            return false;
        }
        isDoubleClick = true;
        dblShape = mouseHitProduct(event);
        if(dblShape!=null){
            showMaskDialog(1);
            clearTimeout(clickTimeOut);
            isDoubleClick = false;
            clickTimeOut = null;
        }
    }

    //单机事件分类
    function clickListener(event){
        if(clickTimeOut==null){
            clickTimeOut = setTimeout(function(){
                if(!isDoubleClick){
                    clickTimeOut = null;
                }
            },500);
        }

        if(lineing){
            var hit = mouseHitProduct(event);
            if(beginPoint==null&&hit!=null){
                beginPoint = hit;
            }else{
                stopPoint = hit;
                lineing = false;
                if(stopPoint!=null){
                    //检测是否有相同连线
                    var isAdd = true;
                    for(var i = 0;i<relations.length;i++){
                        if(typeof(relations[i])=="undefined"){
                            continue;
                        }
                        if(relations[i].beginPoint.id==beginPoint.id&&relations[i].stopPoint.id==stopPoint.id){
                            isAdd = false;
                            break;
                        }
                    }
                    if(isAdd){
                        relations[relations.length] = {beginPoint:beginPoint,stopPoint:stopPoint};
                    }
                }
                drawScreen();
                beginPoint = null;
                stopPoint = null;
                lineing = true;
            }
        }
        if(deleteLine){
            var hit = mouseHitDelete(event);
            if(hit!=null){
                var i = 0;
                for(i = 0;i<relations.length;i++){
                    var relation = relations[i];
                    if(typeof(relation)=="undefined"){
                        continue;
                    }
                    if(relation==hit.relation){
                        delete relations[i];
                        break;
                    }
                }
                for(i = 0;i<deleteList.length;i++){
                    var deleteL = deleteList[i];
                    if(typeof(deleteL)=="undefined"){
                        continue;
                    }
                    if(hit==deleteL){
                        delete deleteList[i];
                        break;
                    }
                }

                drawScreen();
            }
        }
        if(deleteProduct){
            var hit = mouseHitProduct(event);
            if(hit==null){
                return;
            }
            var i = 0;
            var bool = false;
            for(i = 0;i<es.length;i++){
                if(typeof(es[i])=="undefined"){
                    continue;
                }
                if(hit.id==es[i].id){
                    delete es[i];
                    bool = true;
                    break;
                }
            }
            for(i = 0;i<relations.length;i++){
                if(typeof(relations[i])=="undefined"){
                    continue;
                }
                if(hit.id == relations[i].beginPoint.id||hit.id == relations[i].stopPoint.id){
                    bool = true;
                    delete relations[i];
                }
            }
            if(bool){
                drawScreen();
            }
        }
    }

    function mouseDownListener(event){
        if(deleteLine||deleteProduct){
            return;
        }
        var hit = mouseHitProduct(event);
        if(hit!=null){
            moveShape = hit;
            dragging = true;
        }
    }

    function mouseUpListener(event){
        dragging = false;
    }

    function mouseMoveListener(event){
        if(dragging){
            var oc = document.getElementById("selectedCanvas");
            var pX = oc.width/oc.getBoundingClientRect().width;
            var pY = oc.height/oc.getBoundingClientRect().height;
            moveShape.x = (event.clientX-oc.getBoundingClientRect().left-moveShape.width/2)*pX;
            moveShape.y = (event.clientY-oc.getBoundingClientRect().top-moveShape.height/2)*pY;
            for(var i = 0;i<relations.length;i++){
                var relation = relations[i];
                if(typeof(relation)=="undefined"){
                    continue;
                }
                if(relation.beginPoint.id==moveShape.id){
                    relation.beginPoint.x = moveShape.x;
                    relation.beginPoint.y = moveShape.y;
                }
                if(relation.stopPoint.id==moveShape.id){
                    relation.stopPoint.x = moveShape.x;
                    relation.stopPoint.y = moveShape.y;
                }
            }
            drawScreen();
        }
        if(lineing){
            if(beginPoint!=null){
                drawScreen();
            }
        }
    }

    function mouseOutListener(event){
        //画线状态需要处理下
        if(lineing){
            beginPoint = null;
            stopPoint = null;
            drawScreen();
        }
    }

    function drag(event){
        // $.modalz("/src/app/views/contain_jenkins.html", "新增", 400, 200);
        dragProduct = event.target;
    }

    function allowDrop(event){
        event.preventDefault();
    }

    //场景处理，先清后画
    function drawScreen(){
        var oc = document.getElementById("selectedCanvas");
        var ctx = oc.getContext("2d");
        ctx.clearRect(0,0,oc.width,oc.height);
        drawShapes();
    }

    //绘画场景
    function drawShapes(){
        drawProducts();
        drawLines();
        drawNowLine();
        drawDeletes();
    }

    //删除产品时，判断鼠标撞击
    function mouseHitProduct(event){
        var mouseXY = getMouseXY(event);
        for(var i = 0;i<es.length;i++){
            if(typeof(es[i])=="undefined"){
                continue;
            }
            if(mouseXY.mouseX>=es[i].x&&mouseXY.mouseX<=es[i].x+es[i].width&&
                mouseXY.mouseY>=es[i].y&&mouseXY.mouseY<=es[i].y+es[i].height){
                return es[i];
            }
        }

        return null;
    }

    //删除连线时，判断鼠标撞击
    function mouseHitDelete(event){
        var mouseXY = getMouseXY(event);
        for(var i = 0;i<deleteList.length;i++){
            if(typeof(deleteList[i])=="undefined"){
                continue;
            }
            if(mouseXY.mouseX>=deleteList[i].x&&mouseXY.mouseX<=deleteList[i].x+deleteList[i].width&&
                mouseXY.mouseY>=deleteList[i].y&&mouseXY.mouseY<=deleteList[i].y+deleteList[i].height){
                return deleteList[i];
            }
        }
        return null;
    }

    //获取当前鼠标位置
    function getMouseXY(event){
        var oc = document.getElementById("selectedCanvas");
        var pX = oc.width/oc.getBoundingClientRect().width;
        var pY = oc.height/oc.getBoundingClientRect().height;
        var mouseX = (event.clientX-oc.getBoundingClientRect().left)*pX;
        var mouseY = (event.clientY-oc.getBoundingClientRect().top)*pY;
        return {"mouseX":mouseX,"mouseY":mouseY}
    }

    //开始连线
    function startLineListener(event){
        lineing = !lineing;
        dragging = false;
        deleteLine = false;
        deleteProduct = false;
        lineBtn.className = lineing?"btnLineSelected":"btnLineNormal";
        deleteProductBtn.className = "btnDeleteProductNormal";
        deleteLineBtn.className = "btnDeleteLineNormal";
        deleteList = [];
        drawScreen(event);
    }

    //删除连线
    function deleteLineListener(event){
        lineing = false;
        dragging = false;
        deleteLine = !deleteLine;
        deleteProduct = false;
        deleteLineBtn.className = deleteLine?"btnDeleteLineSelected":"btnDeleteLineNormal";
        deleteProductBtn.className = "btnDeleteProductNormal";
        lineBtn.className = "btnLineNormal";
        if(deleteLine){
            for(var i = 0;i<relations.length;i++){
                var relation = relations[i];
                if(typeof(relation)=="undefined"){
                    continue;
                }
                drawDelete(relation,true);
            }
        }else{
            deleteList = [];
            drawScreen(event);
        }
    }

    //删除产品
    function deleteProductListener(event){
        lineing = false;
        dragging = false;
        deleteLine = false;
        deleteProduct = !deleteProduct;
        deleteProductBtn.className = deleteProduct?"btnDeleteProductSelected":"btnDeleteProductNormal";
        lineBtn.className = "btnLineNormal";
        deleteLineBtn.className = "btnDeleteLineNormal";
        deleteList = [];
        drawScreen();
    }

    //拖拽产品
    function drawOneProduct(event){
        var name = dragProduct.getElementsByTagName("div")[0].innerHTML;
        var id = dragProduct.id;
        var logo = dragProduct.getElementsByTagName("img")[0].src;

        var oc = document.getElementById("selectedCanvas");
        var ctx = oc.getContext('2d');

        var yImg = new Image();
        yImg.src = logo;

        var pX = oc.width/oc.getBoundingClientRect().width;
        var pY = oc.height/oc.getBoundingClientRect().height;
        var x = (event.clientX-oc.getBoundingClientRect().left-yImg.width/2)*pX;
        var y = (event.clientY-oc.getBoundingClientRect().top-yImg.height/2)*pY;
        ctx.drawImage(yImg, x, y,yImg.width*pX,yImg.height*pY);

        index++;
        var product = {};
        product.info = {};//配置信息
        product.name = name;
        product.id = id+"_"+index;
        product.logo = logo;
        product.x = x;
        product.y = y;
        product.width = yImg.width;
        product.height = yImg.height;

        es[es.length] = product;
    }

    function drawProducts(){
        for(var i = 0;i<es.length;i++){
            //命中目标改变
            var product = es[i];
            if(typeof(product)=="undefined"){
                continue;
            }
            drawProduct(product);
        }
    }

    //画产品
    function drawProduct(product){
        var oc = document.getElementById("selectedCanvas");
        var ctx = oc.getContext('2d');
        var yImg = new Image();
        yImg.src = product.logo;
        var pX = oc.width/oc.getBoundingClientRect().width;
        var pY = oc.height/oc.getBoundingClientRect().height;
        ctx.drawImage(yImg, product.x, product.y,yImg.width*pX,yImg.height*pY);
        //绑定显示文件
        if(typeof(product.info.name)!="undefined"){
            drawWord(product);
        }
    }

    function drawWord(product){
        var oc = document.getElementById("selectedCanvas");
        var ctx = oc.getContext('2d');
        ctx.font = "12px Arial";
        product.info.name.length*12;
        var x = product.x-(ctx.measureText(product.info.name).width-product.width)/2;
        var y = product.y+product.height+12+5;
        ctx.fillText(product.info.name,x,y);
    }

    //画线时，箭头实时跟随鼠标
    function drawNowLine(){
        if(lineing&&beginPoint!=null){
            var mouseXY = getMouseXY(event);
            stopPoint = {};
            stopPoint.x = mouseXY.mouseX;
            stopPoint.y = mouseXY.mouseY;
            stopPoint.width = 0;
            stopPoint.height = 0;
            drawLine(beginPoint,stopPoint);
        }
    }

    //画连线
    function drawLine(beginPoint,stopPoint){
        var oc = document.getElementById("selectedCanvas");
        var ctx = oc.getContext("2d");
        var draw = Object.create(Draw);

        var bp = {};
        bp.x = beginPoint.x+beginPoint.width/2;
        bp.y = beginPoint.y+beginPoint.height/2;

        var sp = {};
        var angle;
        if(beginPoint.x<=stopPoint.x&&beginPoint.y<stopPoint.y){
            angle = (stopPoint.x-beginPoint.x)/(stopPoint.y-beginPoint.y);
            if(angle<=0.5){
                sp.x = stopPoint.x+stopPoint.width/2;
                sp.y = stopPoint.y;
            }else if(angle<=2){
                sp.x = stopPoint.x;
                sp.y = stopPoint.y;
            }else{
                sp.x = stopPoint.x;
                sp.y = stopPoint.y+stopPoint.height/2;
            }
        }else if(beginPoint.x>=stopPoint.x&&beginPoint.y>stopPoint.y){
            angle = (beginPoint.x-stopPoint.x)/(beginPoint.y-stopPoint.y);
            if(angle<=0.5){
                sp.x = stopPoint.x+stopPoint.width/2;
                sp.y = stopPoint.y+stopPoint.height;
            }else if(angle<=2){
                sp.x = stopPoint.x+stopPoint.width;
                sp.y = stopPoint.y+stopPoint.height;
            }else{
                sp.x = stopPoint.x+stopPoint.width;
                sp.y = stopPoint.y+stopPoint.height/2;
            }
        }else if(beginPoint.x<stopPoint.x&&beginPoint.y>=stopPoint.y){
            angle = (beginPoint.y-stopPoint.y)/(stopPoint.x-beginPoint.x);
            if(angle<=0.5){
                sp.x = stopPoint.x;
                sp.y = stopPoint.y+stopPoint.height/2;
            }else if(angle<=2){
                sp.x = stopPoint.x;
                sp.y = stopPoint.y+stopPoint.height;
            }else{
                sp.x = stopPoint.x+stopPoint.width/2;
                sp.y = stopPoint.y+stopPoint.height;
            }
        }else if(beginPoint.x>stopPoint.x&&beginPoint.y<=stopPoint.y){
            angle = (stopPoint.y-beginPoint.y)/(beginPoint.x-stopPoint.x);
            if(angle<=0.5){
                sp.x = stopPoint.x+stopPoint.width;
                sp.y = stopPoint.y+stopPoint.height/2;
            }else if(angle<=2){
                sp.x = stopPoint.x+stopPoint.width;
                sp.y = stopPoint.y;
            }else{
                sp.x = stopPoint.x+stopPoint.width/2;
                sp.y = stopPoint.y;
            }
        }
        else{
            sp.x = stopPoint.x+stopPoint.width/2;
            sp.y = stopPoint.y+stopPoint.height/2;
        }
        draw.set(bp,sp);
        draw.paint(ctx);
    }

    function drawLines(){
        for(var i = 0;i<relations.length;i++){
            if(typeof(relations[i])=="undefined"){
                continue;
            }
            drawLine(relations[i].beginPoint,relations[i].stopPoint);
        }
    }

    //显示删除连线按钮
    function drawDelete(relation,bool){
        var oc = document.getElementById("selectedCanvas");
        var ctx = oc.getContext('2d');
        var yImg = new Image();
        yImg.src = "../images/stacklist_image/d.png";
        var pX = oc.width/oc.getBoundingClientRect().width;
        var pY = oc.height/oc.getBoundingClientRect().height;

        var x = relation.beginPoint.x-(relation.beginPoint.x-relation.stopPoint.x)/2;
        var y = relation.beginPoint.y-(relation.beginPoint.y-relation.stopPoint.y)/2;
        x = x+yImg.width/4;
        y = y+yImg.height/4;
        ctx.drawImage(yImg, x, y,yImg.width*pX/2,yImg.height*pY/2);
        if(bool){
            deleteList[deleteList.length] = {relation:relation,x:x,y:y,width:yImg.width/2,height:yImg.height/2};
        }
    }

    function drawDeletes(){
        for(var i = 0;i<deleteList.length;i++){
            var deleteL = deleteList[i];
            if(typeof(deleteL)=="undefined"){
                continue;
            }
            drawDelete(deleteL.relation,false);
        }
    }

    //画网格
    function drawGrid(){
        var i = 0;
        var w = selectedCanvas.width;
        var h = selectedCanvas.height;
        var ctx = selectedCanvas.getContext("2d");
        ctx.strokeStyle='#000';
        ctx.lineWidth=0.5;
        ctx.beginPath();
        for(i = 1;i<h-1;i++){
            ctx.moveTo(0,i*30);
            ctx.lineTo(w,i*30);
        }
        ctx.stroke();
        ctx.closePath();
    }

    function showMaskDialog(type){
        var div = document.createElement("div");
        div.className = "maskDialog";

        var titleDiv = document.createElement("div");
        titleDiv.className = "maskTitle";
        titleDiv.innerHTML = "参数配置";

        var contentDiv = document.createElement("div");
        contentDiv.className = "maskContent";

        var flootDiv = document.createElement("div");
        flootDiv.className = "maskFloot";

        var firstLbl = document.createElement("label");
        firstLbl.style.marginLeft = "10px";
        firstLbl.innerHTML = "名称：";

        var firstInput = document.createElement("input");
        firstInput.style.marginLeft = "5px";
        if(typeof(dblShape.info.name)!="undefined"){
            firstInput.value = dblShape.info.name;
        }
        contentDiv.appendChild(firstLbl);
        contentDiv.appendChild(firstInput);

        var saveBtn = document.createElement("input");
        saveBtn.type = "button";
        saveBtn.value = "确定";
        saveBtn.addEventListener("click",function(){
            //
            if(firstInput.value==""){
                alert("不能为空");
                return false;
            }
            for(var i = 0;i<es.length;i++){
                if(es[i].id==dblShape.id){
                    es[i].info.name = firstInput.value;
                    ///添加属性
                    ///
                    document.body.removeChild(div);
                    drawScreen();//刷新
                    break;
                }
            }
        });

        var channelBtn = document.createElement("input");
        channelBtn.type = "button";
        channelBtn.value = "取消";
        channelBtn.style.marginLeft = "8px";
        channelBtn.addEventListener("click",function(){
            document.body.removeChild(div);
        })

        flootDiv.appendChild(saveBtn);
        flootDiv.appendChild(channelBtn);

        div.appendChild(titleDiv);
        div.appendChild(contentDiv);
        div.appendChild(flootDiv);

        document.body.appendChild(div);
    }
</script>
</body>
</html>
